package com.lagou.controller;

import com.lagou.dubbo.service.IAuthCodeService;
import com.lagou.dubbo.service.IEmailService;
import com.lagou.util.RandomUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/code")
@RefreshScope
public class AuthCodeController {

    @Reference
    private IAuthCodeService authCodeService;

    @Reference
    private IEmailService emailService;

    @Value("${config.email.templates.checkcode.title}")
    private String mailTitle;

    @Value("${config.email.templates.checkcode.content}")
    private String mailContent;

    @Value("${config.code.length}")
    private int codeLength;

    @GetMapping("/create/{email}")
    public boolean createAuthCode(@PathVariable("email") String email) {
        String code = RandomUtil.getCode(codeLength);
        authCodeService.createNewCode(email, code);

        String message = String.format(mailContent, code);
        return emailService.sendEmail(email, mailTitle, message);
    }
    @GetMapping("/validate/{email}/{code}")
    public int validateAuthCode(@PathVariable("email") String email, @PathVariable("code") String code) {
        return authCodeService.validateAuthCode(email, code);
    }
}
